package gui

import (
	"log"
	"strings"

	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
)

type Table struct {
	*tview.Table
	headers []string
	RowData [][]string
}

func NewTable(headers []string) *Table {
	table := tview.NewTable().SetSelectable(true, false).SetFixed(2, 1)
	return &Table{
		Table:   table,
		headers: headers,
		RowData: [][]string{},
	}
}

// 初始化表头
func (t *Table) InitHeaders() {
	for i, header := range t.headers {
		t.SetCell(0, i, tview.NewTableCell(header).
			SetTextColor(tcell.ColorBlue).
			SetBackgroundColor(tcell.ColorDefault).
			SetAttributes(tcell.AttrBold).
			SetAlign(tview.AlignLeft).
			SetSelectable(false).SetMaxWidth(20))
	}
}

// 设置行信息
func (t *Table) SetRowInfo(kvList [][]string) {
	t.RowData = append(t.RowData, kvList...)
	log.Println("Current RowData:", t.RowData)
}

// 刷新表格
func (t *Table) Refresh() {
	t.Clear()
	t.InitHeaders()

	delClickedFunc := func() bool {
		rowIndex, _ := t.GetSelection()
		if rowIndex == 0 {
			return true
		}
		// 首先从 RowData 中删除数据
		key := t.GetCell(rowIndex, 0).Text
		value := t.GetCell(rowIndex, 1).Text
		t.DelRowData(key, value)

		t.RemoveRow(rowIndex)
		return false
	}

	for i, row := range t.RowData {
		for j, value := range row {
			t.SetCell(i+1, j, tview.NewTableCell(value).SetTextColor(tcell.ColorWhite))
		}
		t.SetCell(i+1, len(row), tview.NewTableCell("del").SetClickedFunc(delClickedFunc).SetTextColor(tcell.ColorRed))
	}
}

// 删除行数据
func (t *Table) DelRowData(key, value string) {
	for i, rowDatum := range t.RowData {
		if (value == "del" && rowDatum[0] == key) || (strings.Join(rowDatum, ",") == key+","+value) {
			t.RowData = append(t.RowData[:i], t.RowData[i+1:]...)
			break
		}
	}
}

func (t *Table) GetRowData() [][]string {
	return t.RowData
}
